import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Card, Form, Input, Button, Select, Tooltip, Icon } from 'antd';
import classNames from 'classnames';
import { useAntdTable, useBoolean } from '@umijs/hooks';
import { getPageSizeByCardHeight, getDataDictValues } from '@/utils/utils';
import ScrollBar from '@/components/ScrollBar';
import SlickTable from '@/components/SlickTable';
import BusiTypeSelect from './components/BusiTypeSelect';
import request from '@/utils/request';
import styles from './index.less';

function Menu({ size: { height }, form }) {
  const { getFieldDecorator } = form;
  const [resultList, setResultList] = useState([[], [], [], []]); // 组件类型
  // sizePage 计算满屏的pageSize
  const [sizePage, setSizePage] = useState(getPageSizeByCardHeight(height));
  // 查询条件表单集合
  const [paramsObj, setParamsObj] = useState({
    queryType: 'handle',
  });

  // 业务类型选择弹窗
  const { state, setTrue, setFalse } = useBoolean(false);
  const [busiTypeCheck, setBusiTypeCheck] = useState([]);
  async function init() {
    await Promise.all([
      request('pmc/pms/StaticDataController/getStaticAttr.do', {
        data: {
          busiObjNbr: 'FaultInfo',
          attrNbr: 'serviceOrderStatus',
        },
      }),
      request('pmc/pms/StaticDataController/getStaticAttr.do', {
        data: {
          busiObjNbr: 'FaultInfo',
          attrNbr: 'importanceLevel',
        },
      }),
      request('pmc/pms/StaticDataController/getStaticAttr.do', {
        data: {
          busiObjNbr: 'FaultInfo',
          attrNbr: 'sourceFrom',
        },
      }),
      request('pmc/pms/StaticDataController/getStaticAttr.do', {
        data: {
          busiObjNbr: 'FaultInfo',
          attrNbr: 'faultDesc',
        },
      }),
    ])
      .then(res => {
        setResultList(res);
      })
      .finally(() => {});
  }

  useEffect(() => {
    init();
  }, []);

  // flow fix-label
  // 当窗口高度变化将重置pageSize
  useEffect(() => {
    setSizePage(getPageSizeByCardHeight(height));
  }, [height]);

  const getTable = ({ current, pageSize, paramsObj }) => {
    return request('oms/serviceOrder/queryServiceOrderPage', {
      data: {
        pageNum: current,
        pageSize,
        ...paramsObj,
      },
    }).then(res => {
      if (Array.isArray(res.data.records)) {
        return {
          total: res.data.total,
          data: res.data.records.map(val => {
            const { children, ...rest } = val;
            return rest;
          }),
        };
      }
      return {
        total: 0,
        data: [],
      };
    });
  };

  // refresh 为useAntable 内置的刷新表格方法
  const { tableProps, refresh } = useAntdTable(
    params => {
      return getTable({ ...params, pageSize: sizePage, paramsObj });
    },
    [paramsObj, sizePage],
    {
      defaultPageSize: sizePage,
    }
  );

  const addOrder = () => {
    router.push('/formDesigner/templates/flow?mode=editMode&formCode=FORM202007311011348708');
  };

  const { pagination, ...restTableProps } = tableProps;

  const query = () => {
    form.validateFields((err, fieldsValue) => {
      // console.log(fieldsValue)
      setParamsObj(fieldsValue);
    });
  };

  const callback = value => {
    console.log(value);
  };

  return (
    <div className={styles.scroll_main}>
      <div className={styles.scroll_left}>
        <Card className="cute" title="查询条件" style={{ height }}>
          <div className={styles.scroll_external}>
            <ScrollBar autoHide autoHeight autoHeightMax={height - 64}>
              <Form className={classNames(styles.scroll_interior, 'flow fix-label')}>
                <Form.Item label="客户编号">
                  {getFieldDecorator('custId', {})(<Input allowClear placeholder="请输入" />)}
                </Form.Item>
                <Form.Item label="电路编号">
                  {getFieldDecorator('prodCol1', {})(<Input allowClear placeholder="请输入" />)}
                </Form.Item>
                <Form.Item label="产品号码">
                  {getFieldDecorator('prodInstId', {})(<Input allowClear placeholder="请输入" />)}
                </Form.Item>
                <Form.Item label="业务类型">
                  {getFieldDecorator('busiType')(
                    <Input
                      readOnly
                      placeholder="请选择"
                      suffix={
                        <Tooltip title="选择">
                          <Icon
                            type="file-search"
                            style={{ color: 'rgba(0,0,0,.45)' }}
                            onClick={() => {
                              setTrue();
                            }}
                          />
                        </Tooltip>
                      }
                    />
                  )}
                </Form.Item>
                <Form.Item label="工单来源">
                  {getFieldDecorator(
                    'sourceFrom',
                    {}
                  )(
                    <Select allowClear placeholder="请选择">
                      {resultList[2].map(item => {
                        return (
                          <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                        );
                      })}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label="工单状态">
                  {getFieldDecorator(
                    'serviceOrderStatus',
                    {}
                  )(
                    <Select allowClear placeholder="请选择">
                      {resultList[0].map(item => {
                        return (
                          <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                        );
                      })}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label="工单等级">
                  {getFieldDecorator(
                    'importanceLevel',
                    {}
                  )(
                    <Select allowClear placeholder="请选择">
                      {resultList[1].map(item => {
                        return (
                          <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                        );
                      })}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label="受理人">
                  {getFieldDecorator('acceptStaff', {})(<Input allowClear placeholder="请输入" />)}
                </Form.Item>
                <Form.Item label="受理开始时间">
                  {getFieldDecorator('beginTime', {})(<Input allowClear placeholder="请输入" />)}
                </Form.Item>
                <Form.Item label="受理结束时间">
                  {getFieldDecorator('endTime', {})(<Input allowClear placeholder="请输入" />)}
                </Form.Item>
                <Form.Item className="text-right padding-top">
                  <Button
                    type="primary"
                    onClick={() => {
                      query();
                    }}
                  >
                    查询
                  </Button>
                </Form.Item>
              </Form>
            </ScrollBar>
          </div>
        </Card>
      </div>
      <div className={styles.scroll_content}>
        <Card
          className="cute"
          title="表格"
          style={{ height }}
          extra={
            <a
              onClick={() => {
                addOrder();
              }}
            >
              + 新建故障单
            </a>
          }
        >
          <SlickTable
            rowKey={record => record.mainId}
            columns={[
              {
                title: '故障单编号',
                dataIndex: 'serviceOrderId',
                ellipsis: true,
              },
              {
                title: '工单来源',
                dataIndex: 'sourceFrom',
                ellipsis: true,
                render: text => {
                  if (text !== null) {
                    const name = resultList[2].filter(function(item) {
                      return item.attrValue === text;
                    });
                    return name[0] ? name[0].attrValueName : '';
                  }
                  return '';
                },
              },
              {
                title: '业务类型',
                dataIndex: 'busiType',
                width: 160,
                ellipsis: true,
              },
              {
                title: '客户名称',
                dataIndex: 'custName',
                ellipsis: true,
              },
              {
                title: '故障简述',
                dataIndex: 'faultDesc',
                ellipsis: true,
                render: text => {
                  if (text !== null) {
                    const name = resultList[3].filter(function(item) {
                      return item.attrValue === text;
                    });
                    return name[0] ? name[0].attrValueName : '';
                  }
                  return '';
                },
              },
              {
                title: '工单状态',
                dataIndex: 'serviceOrderStatus',
                width: 150,
                align: 'center',
                render: text => {
                  if (text !== null) {
                    const name = resultList[0].filter(function(item) {
                      return item.attrValue === text;
                    });
                    return name[0] ? name[0].attrValueName : '';
                  }
                  return '';
                },
              },
              {
                title: '工单等级',
                dataIndex: 'importanceLevel',
                width: 100,
                align: 'center',
                render: text => {
                  if (text !== null) {
                    const name = resultList[1].filter(function(item) {
                      return item.attrValue === text;
                    });
                    return name[0] ? name[0].attrValueName : '';
                  }
                  return '';
                },
              },
              {
                title: '受理人',
                dataIndex: 'col1',
                ellipsis: true,
              },
              {
                title: '受理时间',
                dataIndex: 'createDate',
                width: 220,
                align: 'center',
              },
              {
                title: '附件',
                dataIndex: 'attacheFileUrl',
                width: 100,
                align: 'center',
              },
            ]}
            {...restTableProps}
            data={{
              pagination: {
                ...pagination,
                pageSize: sizePage,
              },
            }}
          />
        </Card>
      </div>
      {state ? (
        <BusiTypeSelect
          visiable={state}
          close={() => {
            setFalse();
          }}
          callback={callback}
          busiTypeCheck={busiTypeCheck}
        />
      ) : null}
    </div>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(Menu));
